import React from 'react';
import ReviewHeader from '../tool/ReviewHeader';
import style from './style.styl';
import {Input, DateSelect, error, TreeList,Button,Checkbox,MulSelect} from '../../../../ui-components';
import util from '../../../../util';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import * as teamAction from '../../../../actions/team.action'
import * as reviewAction from '../../../../actions/review.action' 

import AdminQuestion from './AdminQuestion';
import {makeTeamTree} from '../../../team/TeamManage';

@connect(({team}) => ({team}),dispatch => ({actions: bindActionCreators({...teamAction,...reviewAction }, dispatch)}))
class ReviewAdminAdd extends React.Component {
  static contextTypes = {
    router: React.PropTypes.object
  }
  constructor(props) {
    super(props);
    this.displayName = 'ReviewAdminAdd';
    this.state = {
      fields: {
        templateName: '',
        startTime: '',
        endTime: '',
        selfReviewDeadline: '',
        peerReviewDeadline: '',
        publicDeadline: '',
        questions: [
          '有哪些地方你觉得自己做得不错，并且打算继续保持？',
          '有哪些地方有待改进？',
        ],
        team: [],
        isReviewerAnonymous: 0,
      }
    }
  }
  goBack = () => {
    this.context.router.push(`/review/admin`);
  } 
  componentDidMount() {
    this.props.actions.fetchTeams()
  }

  checkField = (newFields, isSubmit) => {
    const now = Date.now();
    let flag = true;
    for(const key in newFields){
      if(newFields[key] === '' && isSubmit) {
        error('请填写完整');
        flag = false;
      }
      if(key === 'startTime'){
        if(newFields[key] && newFields[key] > now) {
          newFields[key] = '';
          error('工作阶段开始日期不能晚于今日');
          flag = false;
        }
        if(newFields[key] && newFields.endTime && newFields[key] > newFields.endTime){
          newFields[key] = '';
          error('工作阶段开始日期应早于结束日期')
          flag = false;
        };
      }else if (key === 'endTime') {
        if(newFields[key] && newFields[key] > now) {
          newFields[key] = '';
          error('工作阶段结束日期不能晚于今日');
          flag = false;
        }
        if(newFields[key] && newFields.startTime && newFields.startTime >= newFields[key]) {
          newFields[key] = '';
          error('工作阶段开始日期应早于结束日期');
          flag = false;
        }
      }else if (key === 'selfReviewDeadline'){
        if(newFields[key] && newFields[key] <= now) {
          newFields[key] = '';
          error('自评截止日应晚于今日');
          flag = false;
        }
      }else if (key === 'peerReviewDeadline') {
        if(newFields[key] && newFields[key] <= now) {
          newFields[key] = '';
          error('同事反馈截止日应晚于今日');
          flag = false;
        }
        if(newFields[key] && newFields.selfReviewDeadline && newFields[key] <= newFields.selfReviewDeadline){
          newFields[key] = '';
          error('同事反馈截止日应晚于自评截止日');
          flag = false;
        }
      }
      else if (key === 'publicDeadline') {
        if(newFields[key] && newFields[key] <= now) {
          newFields[key] = '';
          error('流程结束日应晚于今日');
          flag = false;
        }
        if(newFields[key] && newFields.peerReviewDeadline && newFields[key] <= newFields.peerReviewDeadline){
          newFields[key] = '';
          error('流程结束时间应晚于同事反馈截止日');
          flag = false;
        }
      }
    }
    return [
      newFields,
      flag,
    ]
  }
  updateField = (value) => {
    const {
      fields
    } = this.state;
    const newFields = {
      ...fields,
      ...value,
    }
    
    this.setState({
      fields:{
        ...this.checkField(newFields)[0]
      }
    });
  }
  createQuestion = (rootTeam) => {
    const {
      fields: _fields
    } = this.state;
    const fields = {..._fields};
    const result = this.checkField(fields, true);
    if(result[1]) {
      if(!fields.questions.length){
        return error('请填写通用问题');
      }
      const {
        team
      } = fields;
      if(!team.length) 
        fields.encryptedTeamIds = [rootTeam.teams[0].teamId];
      else
        fields.encryptedTeamIds = team.map(v => v.teamId);
      fields.team = '';
      this.props.actions.createTemplate(fields, () => {
        this.goBack();
      });
    }
  }
  render() {
    const {
      fields
    } = this.state;
    const { teams } = this.props.team
    const rootTeam = makeTeamTree(teams)[0]
    const timeStamp = 24*60*60*1000-1;
    return (
      <div>
        <ReviewHeader title={'发起反馈活动'} goBack={this.goBack} />
        <div className={style['page']}>
          <div className={style['field-box']}>
            <label>活动名称</label>

            <Input
              autoFocus
              onChange={e => this.updateField({'templateName': e.target.value})}
              value={fields.templateName}
              width={'610px'}
            />
          </div>
          <div className={style['field-box']}>
            <label>工作阶段<aside>指本次活动的工作阶段</aside></label>
            <div className={style['field-group']}>
              <DateSelect
                time={!util.isNull(fields.startTime)? util.time(fields.startTime, '-'): ''}
                onChange={v => this.updateField({'startTime':v + timeStamp})}
                width={'280px'}
              />
              <p>到</p>
              <DateSelect
                time={!util.isNull(fields.endTime)? util.time(fields.endTime, '-'): ''}
                onChange={v => this.updateField({'endTime':v + timeStamp})}
                width={'280px'}
              />
            </div>
            <aside>例如，针对2016年Q1的工作进行反馈，则工作阶段为2016年01月01日至2016年07月01日</aside>
          </div>
          <div className={style['field-box']}>
            <label>自评截止日<aside>员工需要在此日期前提交自评</aside></label>
            <DateSelect
              time={!util.isNull(fields.selfReviewDeadline)? util.time(fields.selfReviewDeadline, '-'): ''}
              onChange={v => this.updateField({'selfReviewDeadline':v + timeStamp})}
              width={'280px'}
            />
          </div>
          <div className={style['field-box']}>
            <label>同事反馈截止日<aside>员工需要在此日期前提交同事反馈</aside></label>
            <DateSelect
              time={!util.isNull(fields.peerReviewDeadline)? util.time(fields.peerReviewDeadline, '-'): ''}
              onChange={v => this.updateField({'peerReviewDeadline':v + timeStamp})}
              width={'280px'}
            />
          </div>
          <div className={style['field-box']}>
            <label>流程结束日<aside>流程结束后，员工将能够看到所有人对自己的反馈</aside></label>
            <DateSelect
              time={!util.isNull(fields.publicDeadline)? util.time(fields.publicDeadline, '-'): ''}
              onChange={v => this.updateField({'publicDeadline':v + timeStamp})}
              width={'280px'}
            />
          </div>
           <div className={style['field-box']}>
            <label>通用问题<aside>反馈活动中，要求所有人回答的问题</aside></label>
            <AdminQuestion value={fields.questions} onChange={v => this.updateField({'questions': v})} />
          </div>
          <div className={style['field-box']}>
            <label>参与活动的部门</label>
            <MulSelect 
              placeholder="默认全部门"
              value={[...fields.team]}
              getItemAttrs={(item) => {
                return {
                  label: item.teamName,
                  img: item.avatarUrl,
                }
              }}
              selectItemStyle={style['select-item']}
              root={rootTeam}
              tree
              onClick={value => this.updateField({'team': value})}
            />
          </div>
          <div className={style['field-box']}>
            <label>可见性</label>
            <label>
              <input
                type="checkbox" 
                onChange={(e) => {
                  const flag = e.target.checked;
                  this.updateField({'isReviewerAnonymous': +flag})
                }}
                checked={!!fields.isReviewerAnonymous}
              />
              <aside>这是匿名反馈活动，仅HR可以看到反馈者姓名</aside>
            </label>
          </div>
          
          <Button label={'发起活动'} className={style['question-sub']} onClick={this.createQuestion.bind(this,rootTeam)} />

        </div>
      </div>
    );
  }
}

export default ReviewAdminAdd;
